/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { Component } from "react";
import { connect } from "dva";
import PageHeaderLayout from "@/layouts/PageHeaderLayout";
import StandardTable from "@/components/StandardTable";
import PopoverInfo from "@/components/PopoverInfo";
import { Form, Input, Button, Col, Row } from "antd";
import { debounce, isEmpty } from "lodash";
import { getPageQuery } from "@/utils/utils";
import Derivative from "../Derivative";
import styles from "../style.less";
import Modal from "./Modal";

const FormItem = Form.Item;

@connect(({ clientManage, loading, setting: { options = {} } = {} }) => ({
  clientManage,
  isYzAccount: options.key === "yz",
  getList: loading.effects["clientManage/getClientManageList"],
}))
@Form.create()
class Index extends Component {
  handleSearch = debounce(
    e => {
      e.preventDefault();
      this.getList(1);
    },
    500,
    {
      leading: true,
      trailing: false,
    }
  );

  handleTableChange = debounce(
    pagination => {
      const { current } = pagination;
      this.setState({
        currentPage: current,
      });
      this.getList(current);
    },
    500,
    {
      leading: true,
      trailing: false,
    }
  );

  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      title: "",
      type: null,
      record: null,
      disabled: true,
      selectedRows: [],
      currentPage: 1,
      // client | derivative
      sourceType: "client",
    };
    this.columns = [
      {
        title: "公司名称",
        key: "company_site_id",
        dataIndex: "customer",
        align: "center",
      },
      {
        title: "联系人",
        key: "linkman_name",
        dataIndex: "linkman_name",
        align: "center",
      },
      {
        title: "联系电话",
        key: "linkman_mobile",
        dataIndex: "linkman_mobile",
        align: "center",
      },
      {
        title: "业务员",
        key: "courier_id",
        align: "center",
        render: (text, record) => {
          const { courier_name, courier_phone } = record;
          return `${courier_name}-${courier_phone}`;
        },
      },
      {
        title: "操作",
        align: "center",
        render: (text, record) => {
          return <a onClick={this.onTriggerModal.bind(this, true, "edit", record)}>编辑</a>;
        },
      },
    ];
  }

  componentDidMount() {
    this.getList(1);
    const searchParams = getPageQuery();
    if (!isEmpty(searchParams)) {
      this.setState({
        sourceType: searchParams.type,
      });
    }
  }

  onTriggerModal(open, type, record) {
    let title = "修改客户信息";
    if (type === "add") {
      title = "添加客户信息";
    }
    this.formRef.props.form.resetFields();
    this.setState({
      visible: open,
      title,
      type,
      record,
    });
  }

  getFormValues = then => {
    const { form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const values = {
        ...fieldsValue,
      };
      values.size = 100;

      this.setState({
        formValues: values,
      });
      then(values);
    });
  };

  getList = page => {
    const { dispatch } = this.props;
    this.getFormValues(res => {
      dispatch({
        type: "clientManage/getClientManageList",
        payload: {
          page,
          ...res,
        },
      });
    });
  };

  modalFormRef = formRef => {
    this.formRef = formRef;
  };

  onRowSelect = selectedRows => {
    const disabled = selectedRows.length == 0;
    this.setState({
      disabled,
      selectedRows,
    });
  };

  deletClient() {
    const { selectedRows, currentPage } = this.state;
    const { dispatch } = this.props;

    const id = selectedRows
      .map(item => {
        return item.id;
      })
      .join(",");

    dispatch({
      type: "clientManage/deleteClientInfo",
      payload: { id },
    }).then(() => {
      this.setState({ selectedRows: [], disabled: true });
      this.getList(currentPage);
    });
  }

  render() {
    const {
      visible,
      title,
      type,
      formValues,
      record,
      disabled,
      selectedRows,
      sourceType,
    } = this.state;
    const {
      form: { getFieldDecorator },
      getList,
      clientManage: { clientManageList },
      isYzAccount,
    } = this.props;

    return (
      <PageHeaderLayout
        title="客户管理"
        tabActiveKey={sourceType}
        onTabChange={key => {
          this.setState({
            sourceType: key,
          });
        }}
        tabList={[
          {
            key: "client",
            tab: (
              <span>
                企业客户管理
                <PopoverInfo>
                  为业务员创建企业客户信息，创建的企业客户信息可用用来核销代收货款，
                  <br />
                  同时该业务员APP客户管理中会同步该企业信息。
                </PopoverInfo>
              </span>
            ),
          },
          {
            ...(isYzAccount
              ? {
                  key: "derivative",
                  tab: (
                    <span>
                      微商客户管理
                      <PopoverInfo>
                        方便智慧快递平台管理人员直接给自己发展的微商客户建立账号及绑定业务员账号，快速设置相关单号源。
                      </PopoverInfo>
                    </span>
                  ),
                }
              : {}),
          },
        ]}
      >
        <div className={styles.main} style={{ position: "relative" }}>
          {sourceType === "client" ? (
            <>
              <Form layout="inline" onSubmit={this.handleSearch} style={{ marginBottom: 24 }}>
                <FormItem>
                  {getFieldDecorator("search", {
                    initialValue: "",
                  })(
                    <Input
                      allowClear
                      style={{ width: 300 }}
                      placeholder="可根据公司名称、联系人或联系电话搜索"
                    />
                  )}
                </FormItem>
                <FormItem>
                  {getFieldDecorator("kdySearch", {
                    initialValue: "",
                  })(
                    <Input
                      allowClear
                      style={{ width: 300 }}
                      placeholder="可根据业务员手机号或者姓名搜索"
                    />
                  )}
                </FormItem>
                <FormItem>
                  <Button type="primary" icon="search" htmlType="submit" loading={getList}>
                    查询
                  </Button>
                </FormItem>
                <FormItem>
                  <Button type="primary" onClick={() => this.onTriggerModal(true, "add")}>
                    添加新客户
                  </Button>
                </FormItem>
              </Form>
              <StandardTable
                rowKey={r => r.id}
                columns={this.columns}
                data={clientManageList}
                loading={getList}
                pagination={{ pageSize: "100" }}
                selectedRows={selectedRows}
                onSelectRow={this.onRowSelect}
                onChange={this.handleTableChange}
              />
              <Row style={{ position: "absolute", bottom: "45px" }}>
                <Col>
                  <Button disabled={disabled} type="primary" onClick={this.deletClient.bind(this)}>
                    删除
                  </Button>
                </Col>
              </Row>
              <Modal
                wrappedComponentRef={this.modalFormRef}
                visible={visible}
                okText="确定"
                type={type}
                title={title}
                record={record}
                searchFormValue={formValues}
                hideModal={() => this.onTriggerModal(false)}
              />
            </>
          ) : (
            <Derivative />
          )}
        </div>
      </PageHeaderLayout>
    );
  }
}

export default Index;
